package cn.gson.crm.controller.onsales;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hibernate.engine.transaction.jta.platform.internal.SynchronizationRegistryBasedSynchronizationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.OrderDao;
import cn.gson.crm.model.dao.OrderDetailDao;
import cn.gson.crm.model.dao.ProductDao;
import cn.gson.crm.model.dao.QuotationDao;
import cn.gson.crm.model.dao.QuotationDetailsDao;
import cn.gson.crm.model.entity.Order;
import cn.gson.crm.model.entity.OrderDetail;
import cn.gson.crm.model.entity.Quotation;
import cn.gson.crm.model.entity.QuotationDetails;
import cn.gson.crm.model.entity.SalesOpportunity;
import cn.gson.crm.service.OrderDetailService;

/**
 * 订单明细 1获取订单明细列表,分页 2查出订单是否有报价单。 3保存在订单生成时的多条订单明细 4在订单明细中逐条添加订单明细
 * 5.根据订单id查询订单明细
 * 
 * @author hzl
 * @date 2018年4月12日
 * @time 下午10:26:57
 */
@Controller
@RequestMapping("crm/orderDetail")
public class OrderDetailController {
	@Autowired
	OrderDetailDao orderDetailDao;

	@Autowired
	OrderDao orderDao;

	@Autowired
	ProductDao productDao;

	@Autowired
	QuotationDao quotationDao;

	@Autowired
	QuotationDetailsDao quotationDetailsDao;

	@Autowired
	OrderDetailService orderDetailService;

	@GetMapping
	public String orderDetailList() {
		return "onsales/order/order_detail_list";
	}

	// 1获取订单明细列表,分页
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> getlist(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows) {
		return orderDetailService.getlist(page, rows, "订单");
	}

	// 2查出订单是否有报价单。
	@GetMapping("getQuotationDetails/{id}")
	@ResponseBody
	public JSONArray getQuotationDetails(@PathVariable(name = "id") Long id) {
		JSONArray jsonArray = new JSONArray();
		Order order = orderDao.findOne(id);
		SalesOpportunity SalesOpportunity = order.getSalesOpp();
		Quotation quotation = quotationDao.findBySalesOpp(SalesOpportunity);
		if (quotation != null) {
			List<QuotationDetails> qds = quotationDetailsDao.findByQuotation(quotation);
			for (QuotationDetails qd : qds) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("pid", qd.getProduct().getId());
				jsonObject.put("price", qd.getQuotedPrice());
				jsonObject.put("amount", qd.getNum());
				jsonObject.put("money", qd.getQuotedPrice() * qd.getNum());
				jsonObject.put("productName", qd.getProduct().getName());
				jsonArray.add(jsonObject);
			}
		}
		return jsonArray;
	}

	// 3保存在订单生成时的订单明细
	@PostMapping("save/{orderid}")
	@ResponseBody
	public JSONObject saveOrderDetail(@RequestParam("param") String list,
			@PathVariable(name = "orderid") Long orderid) {
		JSONObject result = new JSONObject();
		Order order = orderDao.findOne(orderid);
		double orderMoney = 0;
		if (order == null) {
			result.put("err", "保存失败！");
			return result;
		}
		JSONArray jsonArray = JSONArray.parseArray(list);
		if (jsonArray.size() > 0) {
			for (int i = 0; i < jsonArray.size(); i++) {
				// 遍历 jsonarray 数组，把每一个对象转成 json 对象
				JSONObject obj = jsonArray.getJSONObject(i);
				OrderDetail orderDetail = new OrderDetail();
				// 得到 每个对象中的属性值
				orderDetail.setPrice(obj.getDoubleValue("price"));
				orderDetail.setAmount(obj.getInteger("amount"));
				orderDetail.setNote(obj.getString("note"));
				orderDetail.setMoney(obj.getDoubleValue("price") * obj.getInteger("amount"));
				orderDetail.setProduct(productDao.findOne(obj.getLong("pid")));
				orderDetail.setOrder(order);
				orderDetail.setCustomer(order.getCustomer());
				orderDetail.setEmployee(order.getEmployee());
				orderDetail.setType("订单");
				orderDetail.setState("未发货");
				orderMoney += orderDetail.getMoney();
				orderDetailDao.save(orderDetail);
			}
		}
		order.setOrderMoney(orderMoney);
		orderDao.save(order);
		result.put("order", order);
		return result;
	}

	// 4在订单明细中逐条添加订单明细
	@PostMapping("saveone")
	@ResponseBody
	public JSONObject saveOneOrderDetail(@Valid OrderDetail orderDetail, BindingResult br,
			@RequestParam("productid") Long pid, @RequestParam("orderid") Long oid, @RequestParam("type") String type) {
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败");
		} else {
			Order order = orderDao.findOne(oid);
			orderDetail.setOrder(order);
			orderDetail.setProduct(productDao.findOne(pid));
			orderDetail.setCustomer(order.getCustomer());
			orderDetail.setType(type);
			orderDetail.setState("未发货");
			orderDetailDao.save(orderDetail);
			result.put("success", true);
		}
		return result;
	}
	//根据订单查询订单明细
	@GetMapping("getDetailByOrder/{orderid}")
	@ResponseBody
	public JSONArray getDetailByOrder(@PathVariable(name = "orderid") Long orderid, @RequestParam(value="state",required=false) String state,
			HttpServletRequest req) {
		System.out.println("哈哈哈这里zhixing");
		JSONArray jsonArray = new JSONArray();
		Order order = orderDao.findOne(orderid);
		List<OrderDetail> orderDetails; 
		if(state==null){
			orderDetails = orderDetailDao.findByOrderAndType(order, "订单");
		}else{
			orderDetails = orderDetailDao.findByOrderAndTypeAndState(order, "订单", state);
		}
		for (OrderDetail orderDetail : orderDetails) {
			System.out.println(orderDetail.toString());
			jsonArray.add(orderDetail);
		}
		return jsonArray;
	}
}
